package com.mtzqc.kt

import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.mtzqc.glide.GlideApp
import com.mtzqc.glide.GlideRequest
import com.mtzqc.glide.GlideRequests
import com.mtzqc.img.R
import java.io.File

val IMAGE_ERROR_RESOURCE: Int by lazy {
    R.drawable.lib_img_error
}


inline fun ImageView.load(
    url: Any?,
    manager: GlideRequests = GlideApp.with(this),
) {
    loadImg<Drawable>(url,manager) {
        error(IMAGE_ERROR_RESOURCE)
        CenterCrop()
    }
}

inline fun ImageView.loadAvatar(
    url: Any?,
    manager: GlideRequests = GlideApp.with(this)
    ) {
    loadImg<Bitmap>(url,manager) {
        applyAvatar()
    }
}


/**
 * 加载圆角图片
 */
inline fun ImageView.loadCircle(
    url: Any?,
    radius: Float = 0f, //<=0 圆形 ,大于0:圆角
    manager: GlideRequests = GlideApp.with(this)
) {
    loadImg<Bitmap>(url,manager) {
        if (radius <= 0) {
            applyCircle()
        } else {
            error(IMAGE_ERROR_RESOURCE)
                .transform(
                    CenterCrop(), RoundedCorners(SizeUtils.dp2px(radius))
                )
        }
    }

}

inline fun <reified M> ImageView.loadImg(
    url: Any?,
    manager: GlideRequests = GlideApp.with(this),
    request: (GlideRequest<M>.() -> Unit) = {
        error(IMAGE_ERROR_RESOURCE)
    }
) {
    var isGif = url?.toString()?.contentEquals(".gif") ?: false
    var builder = if (GifDrawable::class.java.isAssignableFrom(M::class.java) || isGif) {
        manager.asGif()
    } else if (Bitmap::class.java.isAssignableFrom(M::class.java)) {
        manager.asBitmap()
    } else if (File::class.java.isAssignableFrom(M::class.java)) {
        manager.asFile()
    } else {
        manager.asDrawable()
    }
    var newBuilder = when (url) {
        is Int -> builder.load(url)
        is Uri -> builder.load(url)
        is File -> builder.load(url)
        is Drawable -> builder.load(url)
        is Bitmap -> builder.load(url)
        else -> builder.load(url)
    }
    (newBuilder as GlideRequest<M>).let {
        request.invoke(it)
        it.into(this)
    }
}
